import api from '../../api';
import { message } from 'antd';
import { isZiGuanEvir } from '../../utils/commonFunc';

const formatDecimal = (num, decimal) => {
  num = num.toString();
  const index = num.indexOf('.');
  if (index !== -1) {
    num = num.substring(0, decimal + index + 1);
  } else {
    num = num.substring(0);
  }
  return Number(parseFloat(num).toFixed(decimal));
};
export default {
  namespace: 'tradeHoldM',
  state: {},
  effects: {
    // 查询持仓可用信息
    *getPosition({ payload, callback }, { call, put }) {
      const { tradingcode, exchangecode, fundId, maatApi, hkType, securityType } = payload;
      const args = { tradingcode, exchangecode, fundId, securityType };
      let response;
      let withMAAT = false;
      if (maatApi) {
        // 判断当前环境是不是资管
        const temp = isZiGuanEvir();
        if (!!temp && temp['iv-user']) withMAAT = true;
      }
      if (withMAAT) {
        // 资管
        response = yield call(api.etfOrderApi.getPositionWithMAAT, args);
      } else {
        // maat
        // eslint-disable-next-line no-lonely-if
        if (hkType == '2') {
          // 如果入参有hkType='2',则为港股通模式
          const arg = {
            tradingcode,
            exchangecode,
            fundId,
            hkType: '2',
            securityType,
          };
          response = yield call(api.etfOrderApi.getPosition, arg);
        } else if (hkType == '1') {
          // 默认模式
          const arg = { tradingcode, exchangecode, fundId, securityType };
          response = yield call(api.etfOrderApi.getPosition, arg);
        } else if (hkType == '3') {
          // 股指期货模式
          const arg = { portfolio: fundId };
          response = yield call(api.etfOrderApi.getPositionStockIndex, arg);
          if (response && response.code == 0) {
            response.data &&
              response.data.dataSource &&
              response.data.dataSource.map((item) => {
                item.price = formatDecimal(item.price, 2); // 保留两位小数，但不四舍五入
              });
            callback(response.data);
          } else {
            callback();
            message.error(response && response.msg ? response.msg : '查询持仓信息失败!');
          }
          return;
        }
      }
      if (response && response.success) {
        callback(response.data);
      } else {
        callback();
        message.error(response && response.msg ? response.msg : '查询持仓信息失败!');
      }
    },
    // 查询持仓可用信息 新接口
    *queryAvailablePosition({ payload, callback }, { call, put }) {
      const { hkType } = payload;
      delete payload.hkType;
      let response;
      if (hkType == '2') {
        // 如果入参有hkType='2',则为港股通模式
        // let arg = {
        //   tradingCode: tradingcode,
        //   exchangeCode: exchangecode,
        //   fundId: fundId,
        //   hkType: '2',
        //   securityType: securityType,
        // };
        // response = yield call(api.etfOrderApi.getPosition, arg);
      } else if (hkType == '1') {
        // 默认模式
        response = yield call(api.queryAvailablePosition, payload);
      } else if (hkType == '3') {
        // 股指期货模式
        // let arg = { portfolio: fundId };
        // response = yield call(api.etfOrderApi.getPositionStockIndex, arg);
        // if (response && response.code == 0) {
        //   response.data &&
        //     response.data.dataSource &&
        //     response.data.dataSource.map((item) => {
        //       item.price = formatDecimal(item.price, 2); //保留两位小数，但不四舍五入
        //     });
        //   callback(response.data);
        // } else {
        //   callback();
        //   message.error(response && response.msg ? response.msg : '查询持仓信息失败!');
        // }
        // return;
      }
      if (response && response.code == 0) {
        callback(response.data);
      } else {
        callback();
        message.error(response?.msg || '查询持仓信息失败!');
      }
    },
    // 根据productGroupId（产品组id）查询持仓可用信息
    *getPositionByProductGroupId({ payload, callback }, { call, put }) {
      const response = yield call(api.etfOrderApi.getPositionByProductGroupId, payload);
      if (response && response.success == true) {
        callback(response.data);
      } else {
        callback();
        message.error(`查询持仓信息失败，失败原因：${response?.message}`);
        console.error(
          `查询持仓信息失败，失败原因：${response?.message}`,
          '接口名称： queryHoldqueryPositongByCodeList 接口：inventoryManagement-server/api/v2/inventory/management/holdInfo/queryHoldqueryPositongByCodeList',
        );
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
